package com.geeklan.smart.data.remote.tcp;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

public class OkHttpWebSocket {

    public static void main(String[] args) {
        String serverUrl = "ws://192.168.25.1:8869/"; // 替换为实际服务器地址

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(serverUrl)
                .build();

        WebSocketListener listener = new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                System.out.println("WebSocket连接成功！");
                webSocket.send("你好，服务器！");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                System.out.println("收到服务器消息: " + text);
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                System.out.println("WebSocket正在关闭...");
                webSocket.close(1000, null);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                System.err.println("WebSocket连接失败: " + t.getMessage());
            }
        };

        WebSocket webSocket = client.newWebSocket(request, listener);

        // 保持客户端运行以监听消息
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            webSocket.close(1000, "客户端关闭");
            client.dispatcher().executorService().shutdown();
        }));
    }
}